package com.csx.base.design.structure.proxy.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

/**
 * @author cuisongxu
 * @date 2022/9/22 12:16
 */
public class BlackListFilter implements InvocationHandler {

    private final List<String> blackList = Arrays.asList("电影", "游戏", "音乐", "小说");

    /**
     * 被代理对象
     */
    private final Object origin;


    public BlackListFilter(Object origin) {
        // 注入被代理对象
        this.origin = origin;
        System.out.println("开启黑名单过滤功能...");
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        String arg = args[0].toString();
        for (String keyword : blackList) {
            // 包含黑名单中的字样
            if(arg.contains(keyword)) {
                System.out.println("禁止访问: " + arg);
                return null;
            }
        }
        // 调用被代理对象方法
        System.out.println("校验通过,转向实际业务");
        return method.invoke(origin, arg);
    }
}
